<?php
// +---------------------------------------------------------------------+
// | OneBase    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/OneBase                      |
// +---------------------------------------------------------------------+

namespace app\common\logic;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;


/**
 * 文件处理逻辑
 */
class File extends LogicBase
{
    
    /**
     * 图片上传
     * small,medium,big
     */
    public function pictureUpload($name, $thumb_config = ['small' => 100, 'medium' => 500, 'big' => 1000])
    {

        if(!getConfig('qiniu_switch')){
            //网站上传图片
            $object_info = request()->file($name);
            $sha1  = $object_info->hash();

            $picture_info = $this->modelPicture->getInfo(['sha1' => $sha1], 'id,name,path,sha1');

            if (!empty($picture_info)) { return $picture_info; }

            $object = $object_info->move(PATH_PICTURE);

            $save_name = $object->getSaveName();

            $save_path = PATH_PICTURE . $save_name;

            $picture_dir_name = substr($save_name, 0, strrpos($save_name, DS));

            $filename = $object->getFilename();

            $thumb_dir_path = PATH_PICTURE . $picture_dir_name . DS . 'thumb';

            !file_exists($thumb_dir_path) && @mkdir($thumb_dir_path, 0777, true);

            Image::open($save_path)->thumb($thumb_config['small']   , $thumb_config['small'])->save($thumb_dir_path  . DS . 'small_'  . $filename);
            Image::open($save_path)->thumb($thumb_config['medium']  , $thumb_config['medium'])->save($thumb_dir_path . DS . 'medium_' . $filename);
            Image::open($save_path)->thumb($thumb_config['big']     , $thumb_config['big'])->save($thumb_dir_path    . DS . 'big_'    . $filename);

            $data = ['name' => $filename, 'path' => $picture_dir_name. SYS_DS_PROS . $filename, 'sha1' => $sha1];

            $result = $this->modelPicture->setInfo($data);

            unset($object);
            $url =false;
            //$url = $this->checkStorage($result);

            if ($result) { $data['id'] = $result; $url && $data['url'] = $url; return $data; }

            return  false;
        }else{
            //原生代码七牛上传文件
            if(!empty($_FILES[$name])){
                $upfile = $_FILES[$name];
            }else{
                $upfile = $_FILES['image'];
            }
//            dd($upfile);

            //6、判断并执行文件上传
            $ext = 'png';  //后缀
            //获取当前控制器名称
            // $controllerName=$this->getContro();
            // 上传到七牛后保存的文件名
            $key = substr(md5($upfile['tmp_name']), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
//        require $_SERVER['DOCUMENT_ROOT'] . '/../vendor/qiniu/php-sdk/autoload.php';
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = getConfig('qiniu_accessKey ');
            $secretKey = getConfig('qiniu_secretKey ');
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket =  getConfig('qiniu_bucket');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $upfile['tmp_name']);
            if ($err !== null) {
                return false;
            }

            $data = ['name' => $key, 'path' => $key, 'sha1' => getRandomStr(10),'url'=>QINIU_URL.'/'. $ret['key']];

            $result = $this->modelPicture->setInfo($data);
            $data['id']=$result;
            return $data;
        }
    }

    /**
     * [将Base64图片转换为本地图片并保存]
     * @param $base64_image_content [要保存的Base64]
     * @param $path [要保存的路径]
     * @return bool|string
     */
    private function base64_image_content($base64_image_content){


        $suffix = "png";
        if (empty($base64_image_content)) {
            return 0;
        }
        if(!getConfig('qiniu_switch')){
            $new_file =date('Ymd',time())."/";
            $basePutUrl = PATH_PICTURE.$new_file;
            $result = explode(',', $base64_image_content);
            if (!file_exists( $basePutUrl)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($basePutUrl,0777,true);
            }
            $ping_url =  md5(uniqid(md5(microtime(true)),true)) . "." . $suffix;
            $file_base64 = str_replace(' ', '+', $result[1]);
            $file_base64 = base64_decode($file_base64);
            $local_file_url = $basePutUrl.$ping_url;
            if (file_put_contents($local_file_url, $file_base64)) {
                $data = ['name' => $ping_url, 'path' => $new_file.$ping_url, 'sha1' => hash("sha1",$ping_url)];
                $result = $this->modelPicture->setInfo($data);
                //$url = $this->checkStorage($result);
                $url =false;
                if ($result) { $data['id'] = $result; $data['path']= get_picture_url($result,false); $url && $data['url'] = $url; return $data; }

            } else {
                return 0;
            }
        }else{
            $ext = 'png'; //后缀
            //获取当前控制器名称
            // 上传到七牛后保存的文件名
            //  $key = substr(md5(substr(str_shuffle('0123456789ABCDEFGHIJKLNMOPQRSTUVWXYZ'), 0, 10)), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;

            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = getConfig('qiniu_accessKey ');
            $secretKey = getConfig('qiniu_secretKey ');
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket =  getConfig('qiniu_bucket');

            $token = $auth->uploadToken($bucket);

            // 去除base64,
            $num = strpos($base64_image_content, ',');
            $image = substr($base64_image_content, $num + 1);
            $str = isset($image) ? $base64_image_content : false;
            $str=explode(',',$str)[1];
            $str = str_replace(' ', '+', $str);
            //生成图片key
            $rand = rand(1111, 9999);
            $now = time();
            $name = 'base64/' . $now . $rand;
            $Key = base64_encode($name);


            if ($str) {
                $qiniu = phpCurlImg("http://upload-z2.qiniu.com/putb64/-1/key/" . $Key, $str, $token);

                //upload.qiniup.com 上传域名适用于华东空间。华北空间使用 upload-z1.qiniu.com，华南空间使用 upload-z2.qiniu.com，北美空间使用 upload-na0.qiniu.com。
                $qiniuArr = json_decode($qiniu, true);

                if (!empty($qiniuArr['key']) && $qiniuArr['key'] == $name) {

                    $data = ['name' => $qiniuArr['key'], 'path' => $qiniuArr['key'], 'sha1' => getRandomStr(10),'url'=>QINIU_URL.'/'. $qiniuArr['key']];
                    $result = $this->modelPicture->setInfo($data);
                    $data['id']=$result;
                    return $data;
                } else {
                    return false;
                }
            }
            return false;
        }

    }

    /**
     * 图片上传
     * small,medium,big
     */
    public function pictureUpload1($data =[])
    {

        $object_info =$data['file'];

        $data=$this->base64_image_content($object_info);
        return $data;
    }
    /**
     * 文件上传
     */
    public function fileUpload($name = 'file')
    {

        if(!getConfig('qiniu_switch')){
            $object_info = request()->file($name);


            $sha1  = $object_info->hash();

            $file_info = $this->modelFile->getInfo(['sha1' => $sha1], 'id,name,path,sha1');

            if (!empty($file_info)) {
                $file_info['url'] = QINIU_URL.'/'.$file_info['url'];
                return $file_info;
            }
//
//        $object = $object_info->move(PATH_FILE);
//
//        $save_name = $object->getSaveName();
            $arr=explode('.',$_FILES['file']['name']);
            $hou=end($arr);

            $file_dir_name = md5($_FILES['file']['name']).'.'.$hou;



            $data = ['name' => $file_dir_name, 'path' => $file_dir_name, 'sha1' => $sha1];

            $result = $this->modelFile->setInfo($data);

            unset($object);

            $url = $this->checkStorage($result, 'uploadFile',$_FILES);

            if ($result) {

                $data['id'] = $result;

                $url && $data['url'] = QINIU_URL.'/'.$url;

                return $data;
            }

            return  false;
        }else{
            //原生代码上传文件
//            $upfile = $_FILES[$name];//获取上传文件信息
            if(!empty($_FILES[$name])){
                $upfile = $_FILES[$name];
            }else{
                $upfile = $_FILES['file'];
            }
            $ext = pathinfo($upfile['name'],PATHINFO_EXTENSION);//获取被上传文件的后缀名
            //6、判断并执行文件上传
            //获取当前控制器名称
            // $controllerName=$this->getContro();
            // 上传到七牛后保存的文件名
            $key = substr(md5($upfile['tmp_name']), 0, 5) . date('YmdHis') . rand(0, 9999) . '.' . $ext;
            // 需要填写你的 Access Key 和 Secret Key
            $accessKey = getConfig('qiniu_accessKey ');
            $secretKey = getConfig('qiniu_secretKey ');
            // 构建鉴权对象
            $auth = new Auth($accessKey, $secretKey);
            // 要上传的空间
            $bucket =  getConfig('qiniu_bucket');
            $token = $auth->uploadToken($bucket);
            // 初始化 UploadManager 对象并进行文件的上传
            $uploadMgr = new UploadManager();
            // 调用 UploadManager 的 putFile 方法进行文件的上传
            list($ret, $err) = $uploadMgr->putFile($token, $key, $upfile['tmp_name']);
            if ($err !== null) {
                return false;
            }

            $data = ['name' => $key, 'path' => $key, 'sha1' => getRandomStr(10),'url'=>QINIU_URL.'/'. $ret['key']];

            $result = $this->modelFile->setInfo($data);
            $data['id']=$result;
            return $data;
        }


    }
    
    /**
     * 云存储
     */
    public function checkStorage($result = 0, $method = 'uploadPicture',$post=[])
    {
        $storage_driver ='Qiniu';
        //$storage_driver = config('storage_driver');

        if (empty($storage_driver)) {
            
            return false;
        }
        
        $driver = SYS_DRIVER_DIR_NAME . $storage_driver;

        $storage_result = $this->serviceStorage->$driver->$method($post);

        $method != 'uploadPicture' ? $this->modelFile->setFieldValue(['id' => $result], 'url', $storage_result) : $this->modelPicture->setFieldValue(['id' => $result], 'url', $storage_result);

        return $storage_result;
    }

    /**
     * 获取指定目录下的所有文件
     * @param null $path
     * @return array
     */
    public function getFileByPath($path = null)
    {
        $dirs = new \FilesystemIterator($path);
        $arr = [];
        foreach ($dirs as $v)
        {
            if($v->isdir())
            {
                $_arr = $this->getFileByPath($path ."/". $v->getFilename());
                $arr = array_merge($arr,$_arr);
            }else{
                $arr[] = $path . "/" . $v->getFilename();
            }
        }
        return $arr;
    }

    public function checkPictureExists($param = []) {
        return '';
        return $this->modelPicture->where('sha1',$param['sha1'])->find();
    }

    public function checkFileExists($param = []) {
        return '';
        $info= $this->modelFile->where('sha1',$param['sha1'])->find();
        if($info){
            $info['url']=QINIU_URL.'/'.$info['url'];
        }
        return $info;
    }
}
